package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private ShopMapper shopMapper;

    @Override
    public Result getBlogById(long id) {
        //1.查询博客信息
        Blog blog = getById(id);
        //查询该博客是否被点赞过
        isBlogLiked(blog);
        //查询关于用户的信息，并插入blog中
        getUserById(blog);
        return Result.ok(blog);
    }

    @Override
    public Result isBlogLiked(Blog blog) {
        String KEY = BLOG_LIKED_KEY + blog.getId();
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请登录后再点赞");
        }
        Double score = stringRedisTemplate.opsForZSet().score(KEY, user.getId().toString());
        blog.setIsLike(score != null);
        return Result.ok();
    }

    /**
     * 这个方法用来排序点赞排名前五的信息
     *
     * @param id
     * @return
     */
    @Override
    public Result BlogLikes(Long id) {
        String KEY = BLOG_LIKED_KEY + id;
        //在redis中获取点赞前五的信息
        Set<String> set = stringRedisTemplate.opsForZSet().range(KEY, 0, 4);
        if (set == null || set.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //将得到的set转化为userDTO
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String idstr = StrUtil.join(",", ids);
        //解决点赞后头像的顺序不一致问题：ORDER BY FIELD（id，5，1）
        List<UserDTO> userDTOs = userService.query().in("id", ids).last("ORDER BY FIELD (id," + idstr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOs);
    }

    /**
     * 保存博客到数据库，并将博客内容推送到其粉丝的收件箱内
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增博客失败");
        }
        //获取所有的粉丝
        List<Follow> users = followService.query().eq("follow_user_id", user.getId()).list();
        if (users == null || users.isEmpty()) {
            return Result.ok();
        }
        //将内容信息发送到所有粉丝的邮箱内
        for (Follow user1 : users) {
            String KEY = "feed:" + user1.getUserId();
            stringRedisTemplate.opsForZSet().add(KEY, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {

        //获取当前用户
        UserDTO user = UserHolder.getUser();

        //在redis内查找收件箱
        String KEY = "feed:" + user.getId();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(KEY, 0, max, offset, 2);
        //解析数据：blogId，minTime（时间戳），offset（偏移量，最小的值出现的次数）
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        Integer os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取blogId
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        //用blogId获取blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD (id ," + idStr + ")").list();
        for (Blog blog : blogs) {
            //查询该博客是否被点赞过
            isBlogLiked(blog);
            //查询关于用户的信息，并插入blog中
            getUserById(blog);
        }
        //返回数据
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setMinTime(minTime);
        result.setOffset(os);
        return Result.ok(result);
    }

    @Override
    public Result queryByShopName(String shopName) {
        Long shopId = shopMapper.selectIdByShopName(shopName);
        List<Blog> blogs = blogMapper.queryByShopName(shopId);
        blogs.forEach(blog -> {
            getUserById(blog);
            isBlogLiked(blog);
        });
        return Result.ok(blogs);
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            getUserById(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        String KEY = BLOG_LIKED_KEY + id;
        Blog blog = getById(id);
        //1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.ok();
        }
        isBlogLiked(blog);

        //2.判断博客是否被喜欢（即isLike字段是true还是false）
        if (BooleanUtil.isFalse(blog.getIsLike())) {
            //3.1false：将数据库内的liked属性值加一
            boolean success = update().setSql("liked =liked +1").eq("id", id).update();
            //3.2将点赞的信息添加到redis中
            if (success == true) {
                stringRedisTemplate.opsForZSet().add(KEY, user.getId().toString(), System.currentTimeMillis());
            }
        } else {
            //4.1true：将数据库内的liked属性减一
            //4.2将点赞的信息从redis中删除
            boolean success = update().setSql("liked =liked - 1").eq("id", id).update();
            if (success == true) {
                stringRedisTemplate.opsForZSet().remove(KEY, user.getId().toString());
            }
        }

        return Result.ok();
    }

    public void getUserById(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
